import { domain } from '@/config';
import navigate from '@/tool/pages';

const qs = require('qs');

const Fly = require('flyio/dist/npm/wx');

const fly = new Fly();

let hasToLogin = true; // 多接口失效引起的连续跳转注册页处理，跳转开关；

// 配置请求根域名
fly.config.baseURL = domain;
fly.config.timeout = 30000;
fly.config.parseJson = true;

//  请求拦截器
fly.interceptors.request.use(
  config => {
    const method = config.method;
    config.showLoading && uni.showLoading({ title: '请求中', mask: true });

    // 正式token
    const accessToken = uni.getStorageSync('accessToken');

    if (accessToken) {
      config.headers.Authorization = `Bearer ${accessToken}`;
    }

    // config.headers['content-type'] = 'application/json';
    if (method === 'POST' || method === 'PUT' || method === 'DELETE') {
      config.body = qs.stringify(config.body);
    }

    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截
fly.interceptors.response.use(
  res => {
    uni.hideLoading();
    if (res.data.code !== 200) {
      switch (res.data.code) {
        case 401:
          uni.removeStorageSync('nickName');
          uni.removeStorageSync('mobile');
          uni.removeStorageSync('accessToken');
          
          // 多接口失效，连续访问处理
          if (hasToLogin) {
            hasToLogin = false;
            navigate({
              page: 'login',
            });
          }
          break;
        default:
          hasToLogin = true;
          uni.showModal({
            content: res.data.msg,
            showCancel: false,
            confirmColor: '#db3d3c',
          });
          break;
      }

      return Promise.reject(res.data);
    }

    setTimeout(() => {
      hasToLogin = true;
    }, 1000);
    return res.data;
  },
  err => {
    uni.hideLoading();
    uni.showModal({
      content: err.response.data.msg || '服务器异常',
      showCancel: false,
      confirmColor: '#db3d3c',
    });

    return Promise.reject(err);
  }
);

export default fly;
